//
//  USChatToolBar.m
//  us
//
//  Created by karry on 2025/4/7.
//

#import "USChatToolBar.h"
#import <UITextView+Placeholder/UITextView+Placeholder.h>
#import "USChatVoiceToolBar.h"
#import "EMAudioRecordUtil.h"
#import "EMAudioPlayerUtil.h"
@interface USChatToolBar()<UITextViewDelegate>

@property (nonatomic) BOOL isWriting;

@property (nonatomic,strong) NSArray <UIButton *>*rightBtns;

@property (nonatomic,strong) USChatVoiceToolBar *voiceToolBar;

@property (nonatomic,strong) UIButton *closeVoiceBtn;

@end

@implementation USChatToolBar


- (instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        [self setupUI];
    }
    return self;
}

- (USChatVoiceToolBar *)voiceToolBar{
    if (!_voiceToolBar) {
        _voiceToolBar = [USChatVoiceToolBar jk_loadInstanceFromNib];
        @weakify(self)
        [[_voiceToolBar.sendBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
            @strongify(self)
            [EMAudioRecordUtil.sharedHelper stopRecordWithCompletion:^(NSString * _Nonnull aPath, NSInteger aTimeLength, NSArray * _Nonnull volumes) {
                @strongify(self)
                !self.didTapSendVoiceBlock?:self.didTapSendVoiceBlock(aPath,aTimeLength,volumes);
                [self makeVoiceToolbarHidden:YES anim:NO];
                [EMAudioRecordUtil.sharedHelper cancelRecord];
                
            }];
        }];
    }
    return _voiceToolBar;
}

- (UIButton *)closeVoiceBtn{
    if (!_closeVoiceBtn) {
        _closeVoiceBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_closeVoiceBtn setImage:[UIImage imageNamed:@"chat_tool_close"] forState:0];
        @weakify(self)
        [[_closeVoiceBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
            @strongify(self)
            [self makeVoiceToolbarHidden:YES anim:YES];
            [EMAudioRecordUtil.sharedHelper cancelRecord];
            [USFeedbackTool notifyWarning];
        }];
    }
    return _closeVoiceBtn;
}



- (void)setupUI{
    
    self.layer.cornerRadius = self.jk_height * 0.5;
    self.layer.masksToBounds = YES;
    
    // 创建磨砂效果
    UIBlurEffect *blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
    UIVisualEffectView *blurEffectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
    blurEffectView.frame = self.bounds;
    blurEffectView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    blurEffectView.userInteractionEnabled = NO; // 如果你希望点击事件穿透磨砂层

    // 设置圆角
    blurEffectView.layer.cornerRadius = self.jk_height * 0.5;
    blurEffectView.layer.masksToBounds = YES;

    // 添加到当前视图
    [self addSubview:blurEffectView];
    [self sendSubviewToBack:blurEffectView]; // 放到底层以避免遮挡其他内容
    
    
    
    CGFloat margin = 8;
    
    self.photoBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.photoBtn setImage:[UIImage imageNamed:@"chat_photo"] forState:0];
    [self addSubview:self.photoBtn];
    
    [self.photoBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(margin);
        make.bottom.mas_offset(-margin);
    }];
    
    self.textView = [[UITextView alloc]initWithFrame:CGRectMake(0, 0, 200, 40)];
    self.textView.font = [UIFont systemFontOfSize:16];
    self.textView.backgroundColor = UIColor.clearColor;
    self.textView.textContainer.lineFragmentPadding = 0;
    self.textView.returnKeyType = UIReturnKeySend;
    self.textView.delegate = self;
    [self addSubview:self.textView];
    self.textView.scrollEnabled = NO;
    self.textView.placeholder = @"发送消息";
    
//    56 -
    [self.textView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_offset(margin);
        make.bottom.mas_offset(-margin);
        make.left.mas_equalTo(self.photoBtn.mas_right).mas_offset(10);
        make.right.mas_offset(-88);
        make.height.mas_greaterThanOrEqualTo(20);
    }];
    
    CGFloat inset = (self.frame.size.height - margin * 2 - self.textView.font.pointSize - 4) * 0.5;
    self.textView.textContainerInset = UIEdgeInsetsMake(inset, 0, inset, 0);

    self.emjBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.emjBtn setImage:[UIImage imageNamed:@"chat_tool_simle"] forState:UIControlStateNormal];
    [self.emjBtn setImage:[UIImage imageNamed:@"chat_tool_keyboard"] forState:UIControlStateSelected];
    [self addSubview:self.emjBtn];
    [self.emjBtn addTarget:self action:@selector(emjAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.emjBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_offset(-margin);
        make.centerY.mas_equalTo(self.photoBtn);
    }];
    
    self.voiceBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.voiceBtn addTarget:self action:@selector(voiceAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.voiceBtn setImage:[UIImage imageNamed:@"chat_tool_voice"] forState:0];
    [self addSubview:self.voiceBtn];
    [self.voiceBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(self.emjBtn.mas_left).mas_offset(-margin);
        make.centerY.mas_equalTo(self.photoBtn);
    }];
    
    self.sendBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.sendBtn.hidden = YES;
    [self.sendBtn addTarget:self action:@selector(sendAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.sendBtn setImage:[UIImage imageNamed:@"chat_post_1"] forState:0];
    [self addSubview:self.sendBtn];
    [self.sendBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_offset(-margin);
        make.centerY.mas_equalTo(self.photoBtn);
    }];
    self.sendBtn.transform = CGAffineTransformMakeScale(0.1, 0.1);
    
    self.rightBtns = @[self.emjBtn,self.voiceBtn];
    
    [self setupRAC];
    
}

- (void)cancelRecord {
    [self makeVoiceToolbarHidden:YES anim:YES];
    [EMAudioRecordUtil.sharedHelper cancelRecord];
}

- (void)makeVoiceToolbarHidden:(BOOL)hidden anim:(BOOL)anim{
    
    if (!hidden) {
        
        self.voiceToolBar.layer.cornerRadius = self.layer.cornerRadius;
        
        [self addSubview:self.voiceToolBar];
        
        self.voiceToolBar.timeLab.hidden = NO;
        [self.closeVoiceBtn setImage:[UIImage imageNamed:@"chat_tool_close"] forState:0];
        self.closeVoiceBtn.transform = CGAffineTransformIdentity;
        self.closeVoiceBtn.alpha = 1;
        
        [self addSubview:self.closeVoiceBtn];
        
        [self.closeVoiceBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_offset(8);
            make.centerY.mas_equalTo(self.voiceToolBar);
        }];
        
        [self.voiceToolBar mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.top.bottom.mas_offset(0);
            make.width.mas_equalTo(40);
        }];
        
        [self layoutIfNeeded];
        
        [self.voiceToolBar mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.top.bottom.mas_offset(0);
            make.right.mas_offset(0);
        }];
        
        
        [UIView animateWithDuration:0.3 delay:0 usingSpringWithDamping:0.8 initialSpringVelocity:0.3 options:UIViewAnimationOptionCurveEaseIn animations:^{
            
            [self layoutIfNeeded];
            
        } completion:^(BOOL finished) {
      
        }];
        
        
    }else{
        
        [self.voiceToolBar.wawBarView reset];
        if (!anim) {
            [self.closeVoiceBtn removeFromSuperview];
            [self.voiceToolBar removeFromSuperview];
            return;
        }
        self.voiceToolBar.timeLab.hidden = YES;

        [self.voiceToolBar mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.top.mas_offset(8);
            make.width.mas_equalTo(0);
            make.bottom.mas_offset(-8);
            
        }];
        
        [UIView animateWithDuration:0.3 delay:0 usingSpringWithDamping:0.8 initialSpringVelocity:0.3 options:UIViewAnimationOptionCurveEaseIn animations:^{
            
            [self layoutIfNeeded];
            
            [self.closeVoiceBtn setImage:[UIImage imageNamed:@"chat_tool_close_s"] forState:0];
            self.closeVoiceBtn.transform =
                CGAffineTransformMakeRotation(-M_PI / 6); // -30°
            self.closeVoiceBtn.transform =
                CGAffineTransformScale(self.closeVoiceBtn.transform, 1.35, 1.35);
            
        } completion:^(BOOL finished) {
            
            [UIView animateWithDuration:0.2 animations:^{
                self.closeVoiceBtn.alpha = 0;
            }completion:^(BOOL finished) {
                [self.closeVoiceBtn removeFromSuperview];
            }];
            
        }];

    }
    
}


- (void)voiceAction:(id)sender{
    
    [USFeedbackTool impactSoft];
    
    [self makeVoiceToolbarHidden:NO anim:YES];

    NSString *fileName = [NSString stringWithFormat:@"voice_%.0f.wav", NSDate.date.timeIntervalSince1970 * 1000];
    NSString *path = [[[EMAudioPlayerUtil sharedHelper] getAudioOrVideoPath] stringByAppendingPathComponent:fileName];
    
    @weakify(self)
    [EMAudioRecordUtil.sharedHelper startRecordWithPath:path completion:^(NSError * _Nonnull error) {
        NSLog(@"开始录音");
    }];
    
    EMAudioRecordUtil.sharedHelper.durationUpdateBlock = ^(float linear, NSTimeInterval duration) {
        @strongify(self)
        self.voiceToolBar.timeLab.text = [self formatDuration:duration];
        [self.voiceToolBar.wawBarView addBarWithVolume:linear];

    };
}

- (NSString *)formatDuration:(NSTimeInterval)duration {
    NSInteger seconds = (NSInteger)duration;
    NSInteger minutes = seconds / 60;
    seconds = seconds % 60;
    return [NSString stringWithFormat:@"%02ld:%02ld", (long)minutes, (long)seconds];
}

- (void)emjAction:(id)sender{
    self.emjBtn.selected = !self.emjBtn.selected;
    
    if (self.emjBtn.isSelected) {
        [self.textView resignFirstResponder];
    }else {
        [self.textView becomeFirstResponder];

    }
    !self.didEmjBlock?:self.didEmjBlock(self.emjBtn.isSelected);
}
- (void)sendAction:(id)sender{
    
    [self sendText:self.textView.text];
    
}

- (void)sendText:(NSString *)text{
    [USFeedbackTool impactSoft];
    !self.didTapSendBlock?:self.didTapSendBlock(text);
    [self clearText];
}

- (void)setupRAC{

 
}

- (void)textViewDidChange:(UITextView *)textView{
    [self handleTextChange];
    
}

- (void)textViewDidBeginEditing:(UITextView *)textView{
    
    !self.didTextBeginChangeBlock?:self.didTextBeginChangeBlock();
    
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    
    if ([text isEqualToString:@"\n"]) {
        // ⏎ 回车键被点击了
        [self sendText:self.textView.text];
        return NO;
    }
    
    return YES;
}



- (void)handleTextChange{
    
    UITextView *textView = self.textView;
    
    self.isWriting = textView.text.length>0?YES:NO;
    
    CGFloat maxHeight = 160;
    CGSize size = [textView sizeThatFits:CGSizeMake(self.textView.bounds.size.width, MAXFLOAT)];

    BOOL shouldScroll = size.height >= maxHeight;
    textView.scrollEnabled = shouldScroll;

    CGFloat newHeight = MIN(size.height, maxHeight);

    BOOL isChange = (newHeight == self.textView.bounds.size.height)?NO:YES;
    
    [textView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(newHeight);
    }];
    
    if (isChange) {
        [self layoutIfNeeded];
        !self.didSizeChangeBlock?:self.didSizeChangeBlock();
    }
}


- (void)clearText{
    self.textView.text = @"";
    [self handleTextChange];
}


- (void)setIsWriting:(BOOL)isWriting{
    if (isWriting == _isWriting) {
        return;
    }
    _isWriting = isWriting;
    
    if (isWriting) {
        
        [self.textView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.right.mas_offset(-60 - 8 - 8);
        }];
        
        self.sendBtn.hidden = NO;
        
        [UIView animateWithDuration:0.3 delay:0 usingSpringWithDamping:0.5 initialSpringVelocity:0.5 options:UIViewAnimationOptionCurveEaseOut animations:^{
            
            [self.rightBtns enumerateObjectsUsingBlock:^(UIButton * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
    
                obj.transform = CGAffineTransformMakeScale(0.0, 0.0);
                
            }];
            
            self.sendBtn.transform = CGAffineTransformIdentity;

            
        } completion:^(BOOL finished) {
    
//            [self.rightBtns enumerateObjectsUsingBlock:^(UIButton * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
//                obj.hidden = YES;
//            }];
        }];
       
        
    }else{
        
        [self.textView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.right.mas_offset(-88);
        }];
        
        [self.rightBtns enumerateObjectsUsingBlock:^(UIButton * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            obj.hidden = NO;
            obj.alpha = 1;
            [obj.layer removeAllAnimations];
        }];
        
        
        self.sendBtn.hidden = YES;
        
        [UIView animateWithDuration:0.3 delay:0 usingSpringWithDamping:0.8 initialSpringVelocity:0.5 options:UIViewAnimationOptionCurveEaseIn animations:^{
            
             [self.rightBtns enumerateObjectsUsingBlock:^(UIButton * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
     
                 obj.transform = CGAffineTransformIdentity;
                 
             }];
            
            self.sendBtn.transform = CGAffineTransformMakeScale(0.65, 0.65);
            
        } completion:^(BOOL finished) {
            
        }];
    }
    
    
}



- (void)layoutSubviews{
    [super layoutSubviews];
    

}

@end
